<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="路段名称" prop="roadName">
        <el-input
          v-model="queryParams.roadName"
          placeholder="请输入路段名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="起点/迄点" prop="nodeName">
        <el-input
          v-model="queryParams.nodeName"
          placeholder="请输入起点/迄点"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['functiontest:InterchangeMileageStatTest:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['functiontest:InterchangeMileageStatTest:export']"
        >导出</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="InterchangeMileageStatTestList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="父节点ID" prop="parentId" />
      <el-table-column label="路段名称" align="center" prop="roadName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_road" :value="scope.row.roadName"/>
        </template>
      </el-table-column>
      <el-table-column label="收费站互通名称" align="center" prop="nodeName" />
      <el-table-column label="匝道1的类型" align="center" prop="ramp1Type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_ramp_length_type" :value="scope.row.ramp1Type"/>
        </template>
      </el-table-column>
      <el-table-column label="匝道长度1" align="center" prop="ramp1Length">
        <template slot-scope="scope">
          <span v-if="scope.row.ramp1Length">{{ scope.row.ramp1Length }}米</span>
        </template>
      </el-table-column>
      <el-table-column label="匝道2的类型" align="center" prop="ramp2Type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_ramp_length_type" :value="scope.row.ramp2Type"/>
        </template>
      </el-table-column>
      <el-table-column label="匝道长度2" align="center" prop="ramp2Length">
        <template slot-scope="scope">
          <span v-if="scope.row.ramp2Length">{{ scope.row.ramp2Length }}米</span>
        </template>
      </el-table-column>
      <el-table-column label="匝道3的类型" align="center" prop="ramp3Type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_ramp_length_type" :value="scope.row.ramp3Type"/>
        </template>
      </el-table-column>
      <el-table-column label="匝道长度3" align="center" prop="ramp3Length">
        <template slot-scope="scope">
          <span v-if="scope.row.ramp3Length">{{ scope.row.ramp3Length }}米</span>
        </template>
      </el-table-column>
      <el-table-column label="匝道4的类型" align="center" prop="ramp4Type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_ramp_length_type" :value="scope.row.ramp4Type"/>
        </template>
      </el-table-column>
      <el-table-column label="匝道长度4" align="center" prop="ramp4Length">
        <template slot-scope="scope">
          <span v-if="scope.row.ramp4Length">{{ scope.row.ramp4Length }}米</span>
        </template>
      </el-table-column>
      <el-table-column label="匝道平均长度" align="center" prop="rampAvgLength">
        <template slot-scope="scope">
          <span v-if="scope.row.rampAvgLength">{{ scope.row.rampAvgLength }}米</span>
        </template>
      </el-table-column>
      <el-table-column label="匝道汇聚点至收费站中心长度" align="center" prop="tollCenterLength">
        <template slot-scope="scope">
          <span v-if="scope.row.tollCenterLength">{{ scope.row.tollCenterLength }}米</span>
        </template>
      </el-table-column>
      <el-table-column label="引道长度" align="center" prop="approachLength">
        <template slot-scope="scope">
          <span v-if="scope.row.approachLength">{{ scope.row.approachLength }}米</span>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['functiontest:InterchangeMileageStatTest:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['functiontest:InterchangeMileageStatTest:add']"
            v-if="scope.row.parentId === 0 || scope.row.parentId === null"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['functiontest:InterchangeMileageStatTest:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改互通里程实测数据测试对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xlsx、xls格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
        <!-- 顶级节点（第一层）只显示路段名称 -->
        <div v-if="form.parentId === 0 || form.parentId === null">
          <el-form-item label="路段名称" prop="roadName">
            <el-select v-model="form.roadName" placeholder="请选择路段名称" clearable filterable>
              <el-option
                v-for="dict in dict.type.sys_road"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <!-- 第二层操作（新增或修改）不显示父节点ID和路段名称 -->
        <div v-else-if="isSecondLevelOperation">
          <el-form-item label="收费站互通名称" prop="nodeName">
            <el-input v-model="form.nodeName" placeholder="请输入收费站互通名称" />
          </el-form-item>
          <el-form-item label="匝道1的类型" prop="ramp1Type">
            <el-select v-model="form.ramp1Type" placeholder="请选择匝道1的类型" clearable filterable>
              <el-option
                v-for="dict in dict.type.sys_ramp_length_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="匝道长度1" prop="ramp1Length">
            <el-input v-model="form.ramp1Length" placeholder="请输入匝道长度1" />
          </el-form-item>
          <el-form-item label="匝道2的类型" prop="ramp2Type">
            <el-select v-model="form.ramp2Type" placeholder="请选择匝道2的类型" clearable filterable>
              <el-option
                v-for="dict in dict.type.sys_ramp_length_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="匝道长度2" prop="ramp2Length">
            <el-input v-model="form.ramp2Length" placeholder="请输入匝道长度2" />
          </el-form-item>
          <el-form-item label="匝道3的类型" prop="ramp3Type">
            <el-select v-model="form.ramp3Type" placeholder="请选择匝道3的类型" clearable filterable>
              <el-option
                v-for="dict in dict.type.sys_ramp_length_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="匝道长度3" prop="ramp3Length">
            <el-input v-model="form.ramp3Length" placeholder="请输入匝道长度3" />
          </el-form-item>
          <el-form-item label="匝道4的类型" prop="ramp4Type">
            <el-select v-model="form.ramp4Type" placeholder="请选择匝道4的类型" clearable filterable>
              <el-option
                v-for="dict in dict.type.sys_ramp_length_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="匝道长度4" prop="ramp4Length">
            <el-input v-model="form.ramp4Length" placeholder="请输入匝道长度4" />
          </el-form-item>
          <el-form-item label="匝道平均长度" prop="rampAvgLength">
            <el-input v-model="form.rampAvgLength" placeholder="匝道平均长度自动计算" readonly />
          </el-form-item>
          <el-form-item label="匝道汇聚点至收费站中心长度" prop="tollCenterLength">
            <el-input v-model="form.tollCenterLength" placeholder="请输入匝道汇聚点至收费站中心长度" />
          </el-form-item>
          <el-form-item label="引道长度" prop="approachLength">
            <el-input v-model="form.approachLength" placeholder="请输入引道长度" />
          </el-form-item>
          <el-form-item label="备注信息" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注信息" />
          </el-form-item>
        </div>
        <!-- 其他层级显示所有字段 -->
        <div v-else>
          <el-form-item label="父节点ID" prop="parentId">
            <treeselect v-model="form.parentId" :options="InterchangeMileageStatTestOptions" :normalizer="normalizer" placeholder="请选择父节点ID" />
          </el-form-item>
          <el-form-item label="路段名称" prop="roadName">
            <el-select v-model="form.roadName" placeholder="请选择路段名称" clearable filterable>
              <el-option
                v-for="dict in dict.type.sys_road"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="收费站互通名称" prop="nodeName">
            <el-input v-model="form.nodeName" placeholder="请输入收费站互通名称" />
          </el-form-item>
          <el-form-item label="匝道1的类型" prop="ramp1Type">
            <el-select v-model="form.ramp1Type" placeholder="请选择匝道1的类型" clearable filterable>
              <el-option
                v-for="dict in dict.type.sys_ramp_length_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="匝道长度1" prop="ramp1Length">
            <el-input v-model="form.ramp1Length" placeholder="请输入匝道长度1" />
          </el-form-item>
          <el-form-item label="匝道2的类型" prop="ramp2Type">
            <el-select v-model="form.ramp2Type" placeholder="请选择匝道2的类型" clearable filterable>
              <el-option
                v-for="dict in dict.type.sys_ramp_length_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="匝道长度2" prop="ramp2Length">
            <el-input v-model="form.ramp2Length" placeholder="请输入匝道长度2" />
          </el-form-item>
          <el-form-item label="匝道3的类型" prop="ramp3Type">
            <el-select v-model="form.ramp3Type" placeholder="请选择匝道3的类型" clearable filterable>
              <el-option
                v-for="dict in dict.type.sys_ramp_length_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="匝道长度3" prop="ramp3Length">
            <el-input v-model="form.ramp3Length" placeholder="请输入匝道长度3" />
          </el-form-item>
          <el-form-item label="匝道4的类型" prop="ramp4Type">
            <el-select v-model="form.ramp4Type" placeholder="请选择匝道4的类型" clearable filterable>
              <el-option
                v-for="dict in dict.type.sys_ramp_length_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="匝道长度4" prop="ramp4Length">
            <el-input v-model="form.ramp4Length" placeholder="请输入匝道长度4" />
          </el-form-item>
          <el-form-item label="匝道平均长度" prop="rampAvgLength">
            <el-input v-model="form.rampAvgLength" placeholder="匝道平均长度自动计算" readonly />
          </el-form-item>
          <el-form-item label="匝道汇聚点至收费站中心长度" prop="tollCenterLength">
            <el-input v-model="form.tollCenterLength" placeholder="请输入匝道汇聚点至收费站中心长度" />
          </el-form-item>
          <el-form-item label="引道长度" prop="approachLength">
            <el-input v-model="form.approachLength" placeholder="请输入引道长度" />
          </el-form-item>
          <el-form-item label="备注信息" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注信息" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInterchangeMileageStatTest, getInterchangeMileageStatTest, delInterchangeMileageStatTest, addInterchangeMileageStatTest, updateInterchangeMileageStatTest, exportInterchangeMileageStatTest, importInterchangeMileageStatTest, importTemplateInterchangeMileageStatTest, fieldAuditInterchangeMileageStatTestBatch, ownerAuditInterchangeMileageStatTestBatch, centerAuditInterchangeMileageStatTestBatch } from "@/api/functiontest/InterchangeMileageStatTest"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import { getUserProfile } from "@/api/system/user"

export default {
  name: "InterchangeMileageStatTest",
  dicts: ['sys_road', 'sys_ramp_length_type'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 互通里程实测数据测试表格数据
      InterchangeMileageStatTestList: [],
      // 互通里程实测数据测试树选项
      InterchangeMileageStatTestOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        roadName: null,
        deptId: null,
        roleId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      deptId: '',
      roleId: '',
    }
  },
  computed: {
    // 判断是否为第一层到第二层的新增
    isFirstToSecondLevel() {
      // 当父节点ID不为0且当前操作为新增时，表示从第一层往第二层的新增
      return (this.form.parentId !== 0 && this.form.parentId !== null && this.form.parentId !== '0') && this.title === "添加互通里程实测数据测试";
    },
    // 判断是否为第二层的修改
    isSecondLevelUpdate() {
      // 当标题为修改且当前数据的parentId不为0（表示是第二层或更深层级的数据）
      // 同时需要判断parentId对应的节点是否为第一层节点
      if (this.title !== "修改互通里程实测数据测试" || !this.form.parentId) {
        return false;
      }
      
      // 查找父节点，判断是否为第一层节点
      const findParentNode = (nodes, parentId) => {
        for (let node of nodes) {
          if (node.id === parentId) {
            return node;
          }
          if (node.children) {
            const found = findParentNode(node.children, parentId);
            if (found) return found;
          }
        }
        return null;
      };
      
      // 查找当前表单数据的父节点
      const parentNode = findParentNode(this.InterchangeMileageStatTestList, this.form.parentId);
      // 如果父节点存在且父节点的parentId为0，则表示当前是第二层的修改
      return parentNode && (parentNode.parentId === 0 || parentNode.parentId === null);
    },
    // 判断是否为第二层操作（新增或修改）
    isSecondLevelOperation() {
      return this.isFirstToSecondLevel || this.isSecondLevelUpdate;
    }
  },
  created() {
    this.getUser().then(() => {
      this.getList();
    });
  },
  methods: {
    getUser() {
      return getUserProfile().then(response => {
        if(response.data.roles[0].roleId != 1) {
          this.deptId = response.data.dept.deptId
        }else{
          this.deptId = null
        }
        this.roleId = response.data.roles[0].roleId
      })
    },
    /** 查询互通里程实测数据测试列表 */
    getList() {
      this.queryParams.deptId = this.deptId
      this.queryParams.roleId = this.roleId
      this.loading = true
      listInterchangeMileageStatTest(this.queryParams).then(response => {
        this.InterchangeMileageStatTestList = this.handleTree(response.data, "id", "parentId")
        this.loading = false
      })
    },
    /** 转换互通里程实测数据测试数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.roadName,
        children: node.children
      }
    },
	/** 查询互通里程实测数据测试下拉树结构 */
    getTreeselect() {
      listInterchangeMileageStatTest().then(response => {
        this.InterchangeMileageStatTestOptions = []
        const data = { id: 0, roadName: '顶级节点', children: [] }
        data.children = this.handleTree(response.data, "id", "parentId")
        this.InterchangeMileageStatTestOptions.push(data)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        roadName: null,
        nodeName: null,
        ramp1Type: null,
        ramp1Length: null,
        ramp2Type: null,
        ramp2Length: null,
        ramp3Type: null,
        ramp3Length: null,
        ramp4Type: null,
        ramp4Length: null,
        rampAvgLength: null,
        tollCenterLength: null,
        approachLength: null,
        remark: null,
        deptId: null,
        roleId: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.getTreeselect()
      if (row != null && row.id) {
        this.form.parentId = row.id
      } else {
        this.form.parentId = 0
      }
      this.open = true
      this.title = "添加互通里程实测数据测试"
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      if (row != null) {
        this.form.parentId = row.parentId
      }
      getInterchangeMileageStatTest(row.id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改互通里程实测数据测试"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInterchangeMileageStatTest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addInterchangeMileageStatTest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有互通里程实测数据测试数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportInterchangeMileageStatTest(queryParams);
      }).then(response => {
        this.$download.saveAs(response, '互通里程实测数据测试.xlsx');
      }).catch(function() {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除互通里程实测数据测试编号为"' + row.id + '"的数据项？').then(function() {
        return delInterchangeMileageStatTest(row.id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    }
  }
}
</script>
